package com.imist.nettybasic4.server.handler;

import com.imist.nettybasic4.protocol.request.CreateGroupRequestPacket;
import com.imist.nettybasic4.protocol.response.CreateGroupResponsePacket;
import com.imist.nettybasic4.session.Session;
import com.imist.nettybasic4.utils.IDUtils;
import com.imist.nettybasic4.utils.SessionUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;

import java.util.ArrayList;
import java.util.List;
@ChannelHandler.Sharable
public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {

    public static final CreateGroupRequestHandler INSTANCE = new CreateGroupRequestHandler();

    protected CreateGroupRequestHandler() {
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, CreateGroupRequestPacket createGroupRequestPacket) throws Exception {
        List<String> userIdList = createGroupRequestPacket.getUserIdList();

        List<String> userNameList = new ArrayList<>();
        // 1.创建一个channel分组；
        ChannelGroup channels = new DefaultChannelGroup(channelHandlerContext.executor());
        // 2.筛选出待加入群聊的用户channel和userName；
        for (String userId: userIdList){
            Channel channel = SessionUtils.getChannel(userId);
            if (channel != null){
                channels.add(channel);
                userNameList.add(SessionUtils.getSession(channel).getUserName());
            }
        }
        //3.创建群聊创建结果的响应
        String groupId = IDUtils.randomId();
        CreateGroupResponsePacket createGroupResponsePacket =new CreateGroupResponsePacket();
        createGroupResponsePacket.setSuccess(true);
        createGroupResponsePacket.setGroupId(groupId);
        createGroupResponsePacket.setUserNameList(userNameList);

        // 4.给每个客户端发送拉群通知；
        channels.writeAndFlush(createGroupResponsePacket);
        System.out.println("群创建成功，id为[ "+createGroupResponsePacket.getGroupId()+"] ," );
        System.out.println("群里面有: "+createGroupResponsePacket.getUserNameList());

        // 5. 保存群组相关的信息
        SessionUtils.bindChannelGroup(groupId, channels);
    }
}
